package com.ia.aistream.manager.framework.notification.impl;

import com.ia.aistream.manager.framework.notification.IEmailManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author guoxy
 */
@Slf4j
@Service
public class EmailManagerImpl implements IEmailManager {
    @Value("${spring.mail.username}")
    private String from;
    @Autowired
    private JavaMailSender sender;

    @Async
    @Override
    public void sendSimpleMessage(String to, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);
        sender.send(message);
        log.info("[ 发送普通邮件 ] 邮件发送成功，收件人：{}",to);
    }

    @Async
    @Override
    public void sendMimeMessage(String to, String subject, String text) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        try {
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(text, true);
            sender.send(messageHelper.getMimeMessage());
            log.info("[ 发送HTML邮件 ] 邮件发送成功，收件人：{}",to);
        } catch (MessagingException e) {
            log.error("[ 发送HTML邮件 ] 向{}发送《{}》邮件错误，异常信息：", to, subject, e);
        }
    }

    @Async
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
            helper.addAttachment(fileName, file);
            sender.send(message);
            //日志信息
            log.info("[ 发送附件邮件 ] 邮件发送成功，收件人：{}",to);
        } catch (MessagingException e) {
            log.info("[ 发送附件邮件 ] 邮件发送失败，收件人：{}，异常信息：", to, e);
        }
    }


}
